// Name: David Andersen

using UnityEngine;
using System.Collections;

public class BucketMove : MonoBehaviour {
	
	public int moveSpeed = 100;
	public int bucketTotal = 3;
	public Transform bucket;
	public GameObject controller;
	public int score;
	public int lifeCounter = 200;
	
	private int bucketCount = 0;
	private Transform[] buckets;
	
	// Use this for initialization
	void Start () {
		
		controller = GameObject.Find("Controller");
		bucketTotal = controller.GetComponent<Controller_Script>().bucketCount;
		bucketCount = bucketTotal - 1;
		
		buckets = new Transform[bucketTotal];
		
		for(int i = 0; i < bucketTotal; i++)
		{
			buckets[i] = Instantiate(bucket, new Vector3(transform.position.x, transform.position.y + 20.0F + (i * 15.0F), transform.position.z), transform.rotation) as Transform;
			buckets[i].transform.parent = transform;
		}
	}
	
	// Update is called once per frame
	void Update () {
		
		Vector3 moveDirection = Vector3.zero;
		Vector3 newPosition = Vector3.zero;
		score = controller.GetComponent<Controller_Script>().score;
				
		if(Input.GetKey(KeyCode.LeftArrow)) moveDirection.x -= 1;
		if(Input.GetKey(KeyCode.RightArrow)) moveDirection.x += 1;
		
		newPosition = moveDirection * (moveSpeed * Time.deltaTime);
		newPosition = transform.position + newPosition;
		newPosition.x = Mathf.Clamp(newPosition.x, -98, 98);
		
		transform.position = newPosition;
		
		if(controller.GetComponent<Controller_Script>().score >= lifeCounter)
		{
			if(bucketCount < (bucketTotal - 1))
			{
				bucketCount ++;
				buckets[bucketCount].active = true;
			}
			lifeCounter += 200;
		}
						
	}
	
	void OnCollisionEnter(Collision collision)
	{
		audio.Play();
		buckets[bucketCount].active = false;		
		bucketCount --;
		if(bucketCount < 0)
		{
			Application.LoadLevel("ScoreTable");
		}
	}
}
